---
--类名: DungeonManager.lua
--创建日期: 2017-6-26
--创建人: 陈小虎
--功能描述:
--修改内容:
--修改日期:
--修改人:
--修改备注:
--
local DungeonInfo = import("..models.vo.DungeonInfo")
local BattleInfos = import("..models.vo.BattleInfos")
local DungeonManager = class("DungeonManager")
local DungeonPassAwardView = import("..views.DungeonPassAwardView")

function DungeonManager:ctor()
    cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

    self:clearBNpcs()
    self:clearPreBNpcs()

    self._dungeonInfo = DungeonInfo.new()
    self._battleInfos = BattleInfos.new()
	self._levelDungeon = false
	self._passDungeonState = false

    EM:on("onReconnectSuccessed", function(event)
    	self:resetDungeonStatus()
		if self:isRace() then
			self:enterDungeonFinishRequest()
		end
    end)
    -- self._doorAnimation = {dir = "armatures/characters/chuansongmen",name = "chuansongmen"}
    -- self._unFinishedDungeonAreas = {}

    -- self._teamUpdateHandle = EM:on("onTeamUpdate", function()
    -- 	self:updateDungeonInfo()
    -- end)
end

function DungeonManager:isDungeonNpc(npcConfig)
	if npcConfig and tonumber(npcConfig.npcCategories) == Enums.NpcVariety.dungeon then
		return true
	end
	return false
end

function DungeonManager:enterDungeonRequest(dungeonId,dungeonSubId,dungeonType,callback,errorCall)
	print("enterDungeonRequest    dungeonId = ",dungeonId,"   dungeonSubId = ",dungeonSubId,"   dungeonType = ",dungeonType)
	app.session:request("pb_dungeon.C2S_EnterDungeon",{dungeonId = dungeonId,dungeonSubId = dungeonSubId,type = dungeonType or "normal"},function(msg)
		dump(msg, "pb_dungeon.C2S_EnterDungeon")
		if msg then
			-- self:parseDungeonInfo(msg.dungeonInfo)
			-- self:parseBattleInfos(msg.battleInfos)
			if callback then
				callback()
			end
		end
	-- end,{block = true},function(msg)
	end,nil,function(msg)
		if msg and msg.content and errorCall then
			errorCall()
		end
	end)
end

-- 退出副本后清理缓存
function DungeonManager:clearDungeon()
	-- 跨服副本清理时要清除跨服队伍数据
	if self._dungeonInfo.isCrossDungeon then
		app:sendMsg("TeamModel", "setTeam", nil)
	end

	self:closeDungeonUi()

	-- 清理数据
	self._dungeonInfo:clear()
	self._dungeonMapId = 0
end

function DungeonManager:leaveDungeonRequest()
	if not self:isInDungeon() then return end
	if self._levelDungeon then return end
	self._levelDungeon = true
	app.session:request("pb_dungeon.C2S_LeaveDungeon",{dungeonUUID = self._dungeonInfo.dungeonUUID},function(msg)
		dump(msg, "pb_dungeon.C2S_LeaveDungeon")
		if msg and msg.ok then
			self:clearDungeon()
		end
	end,nil,function(msg)
		dump(msg, "pb_dungeon.C2S_LeaveDungeon")
	end)
end

function DungeonManager:parseDungeonInfo(dungeonInfo)
	if not dungeonInfo then return end
	self._dungeonInfo:read(dungeonInfo)
	self:updateDungeonInfo()
	if self:isDungeonFinished() then
		self:setPassDungeonState(true)
	else
		self:setPassDungeonState(false)
	end
end

function DungeonManager:parseBattleInfos(battleInfos)
	if not battleInfos then return end
	self._battleInfos:read(battleInfos)
end

function DungeonManager:parseEnterDungeon(msg)
	-- DoEventHandler.clearEventsStatus() 	-- 暂时屏蔽，在战斗内正播放剧情时， 重连或关掉游戏 再进入时会有问题
	self:parseDungeonInfo(msg.dungeonInfo)
	self:parseBattleInfos(msg.battleInfos)
	self:initData()
	self:createBattlePointNpcs()
	self:enterDungeon()
end

function DungeonManager:parseResumeDungeon(msg)
	-- 移除遮罩
	if self:isRace() then
		UIHandler:removePrepareBattleTouchMask()
	end

	FieldManager:stopTouch(false)
	self:parseDungeonInfo(msg.dungeonInfo)
end

function DungeonManager:isRace()
	if self._dungeonInfo then
		return self._dungeonInfo.type == "race"
	end
	return false
end

function DungeonManager:isNormal()
	if self._dungeonInfo then
		return self._dungeonInfo.type == "normal"
	end
	return false
end

function DungeonManager:isSecret()
	if self._dungeonInfo then
		return self._dungeonInfo.type == "secret"
	end
	return false
end

function DungeonManager:noMove()
	FieldManager:stopTouch(true)
	FieldManager:saveAutoWayFindingParams()
	FieldManager:characterStopMove(true)
end

function DungeonManager:dungeonBattleStart(dungeonUUID, index, battleId)
	if BattleManager:isInBattle() then return end -- 已经在战斗内了，就不再触发
	self:setBattleStart(true)
	self:noMove()


	local function battleStart()
		-- 隐藏技能切换按钮
		if self:isRace() then
			EM:notify("onSkillChangeNodeChanged", {status = "hide"}) 
		end
	
		self._battleRequestIndex = index
		self:setAlreadyBattle(index,true)
		-- 朝向 设置为固定朝右
		app.session:request("pb_dungeon.C2S_CreateBattleDungeon",{dungeonUUID = dungeonUUID,index = index,faceTo = Enums.FaceTo.right},function(msg)
			self:handleBattleResponse(msg)
		end,{block = false},function(msg)
			-- if msg and msg.content == "ErrDungeonBattleFinished" then
			-- 	self:setAlreadyBattle(index,true)
			-- end
			self:resetBattleStatus()
			BattleManager:goOutBattle()
			StoryManager:clearAllStatus()
		end)
	end
	
	-- 根据battleId 检查是否有剧情脚本
	local isNeedStory = self._dungeonBattleStorys[battleId]
	if isNeedStory then
		DoEventHandler.startDungeonSubEvent(battleId, battleStart)
	else
		battleStart()
	end
	
end

function DungeonManager:handleBattleResponse(msg)
	if not msg then return end
	if msg.ok then
		self._battleIndex = self._battleRequestIndex
		-- self:setAlreadyBattle(self._battleIndex,true)
	else
		-- self:setAlreadyBattle(self._battleRequestIndex,false)
		self:resetBattleStatus()
		BattleManager:goOutBattle()
		StoryManager:clearAllStatus()
		display.pushToast(L("lua_code_text_502"))
	end
end

function DungeonManager:enterDungeonFinishRequest()
	app.session:request("pb_dungeon.C2S_EnterDungeon_Finish",{},function(msg)
	end,{block = false},function(msg)

	end)
end

function DungeonManager:resetBattleStatus()
	if self:getDungeonMapId() == MapManager:getMapId() then
		self:resetDungeonStatus()
	end
end

function DungeonManager:resetDungeonStatus()
	self:setBattleStart(false)
	FieldManager:stopTouch(false)
end

function DungeonManager:setBattleStart(isStart)
	self._battleStart = isStart
end

function DungeonManager:isBattleStart()
	return self._battleStart
end

function DungeonManager:getDungeonMapId()
	return self._dungeonMapId or 0
end

function DungeonManager:setPassDungeonState(state)
	self._passDungeonState = state
end

function DungeonManager:getPassDungeonState()
	return self._passDungeonState
end

function DungeonManager:init()
	local dC = GD:queryDungeonConfigs()
	if not dC then return end
	self._subKeyTable = {}
	for _,v in pairs(dC) do
		if v.subIDs then
			local idsArray = string.split(v.subIDs,";")
			for _,v1 in pairs(idsArray) do
				self._subKeyTable[tostring(v1)] = v.ID
			end
		end
	end
end

-- 获得开放等级
function DungeonManager:getDungeonOpenLv()
	return self._dungeonOpenLv
end

function DungeonManager:getDungeonTotalId(mapId)
	local subC = GD:queryDungeonSubByMapId(mapId)
	if not subC or not subC.ID then return end
	return self._subKeyTable[tostring(subC.ID)],tonumber(subC.ID)
end

function DungeonManager:getDungeonSubId()
	if self._dungeonInfo then
		return self._dungeonInfo.dungeonSubID
	end
	return nil
end

function DungeonManager:updateBattleRadius(battleId)
	local battle = GD:getCachedValue("battle",battleId)
	local fieldSize = tonumber(battle.battlefieldSize) --战场大小
	local roledefaultlocation = tonumber(GD:getSystemPar("roledefaultlocation",0)) --主角距离左边界的距离
	local initPos = tonumber(battle.initPos) --怪物5号位置距离右边界的距离
	local screenScale = 1 / MapManager:getMap():getGroundScale(Constant.BattleGroundLineNumber)
	if battle.roleSpecialLocation then
		roledefaultlocation = tonumber(battle.roleSpecialLocation)
	end

	return (fieldSize - initPos - roledefaultlocation) / Constant.BattleLogicToSceneScale * screenScale
end

function DungeonManager:initData()
	-- self._dungeonTotalConfig = GD:queryDungeonCfgById(self._dungeonInfo.dungeonID)
	self._subConfig = GD:queryDungeonSubById(self._dungeonInfo.dungeonSubID)
	self._dungeonType = tonumber(self._subConfig.mapType)
	self._dungeonOpenLv = tonumber(self._subConfig.openLv)
	self._dungeonBattleStorys = {}
	local szString = self._subConfig.dungeonBattleStory
	if szString then
		local arrPoints = string.split(szString, "|")
		for _, point in ipairs(arrPoints) do
			self._dungeonBattleStorys[tonumber(point)] = true
		end
	end

	self._battlePoints = {}

	self._initMapScale = MapManager:getMapScale()

	for k,v in pairs(self._battleInfos.battleInfos) do
		local index = v.index
		local fieldPos = "pos" .. index
		local fieldRadius = "radius" .. index
		local fieldBattleID = "battleID" .. index
		local battlePoint = {}
		battlePoint.posx = tonumber(self._subConfig[fieldPos]) or 0
		-- battlePoint.radius = tonumber(self._subConfig[fieldRadius]) or 0
		battlePoint.battleId = tonumber(self._subConfig[fieldBattleID]) or 0
		battlePoint.index = index
		battlePoint.finished = v.finished
		battlePoint.formationID = v.formationID
		battlePoint.formationInfo = v.formationInfo
		local ret = GD:spawnNpcByFormationId(battlePoint.battleId,battlePoint.posx)
		battlePoint.radius = ret and ret.range or 10
		battlePoint.info = ret or {}
		table.insert(self._battlePoints,battlePoint)
	end

	if self._subConfig.mapID then
		self._dungeonMapId = tonumber(self._subConfig.mapID)
	end

	self:updateBattlePointStatus()
	-- 进入副本之后，更新一次任务随从
	FieldManager:updateTeamTaskFollowMercenary()
end

function DungeonManager:isLuckBox()
	local isLuckBox = false
	if self._subConfig then
		isLuckBox = ((tonumber(self._subConfig.luckBox) == 1) and self:isDungeonFinished()) and true or false
	end
	return isLuckBox
end

function DungeonManager:setAlreadyBattle(index,isBattle)
	if not self._battlePoints then return end
	for k,v in pairs(self._battlePoints) do
		if v.index == index then
			v.already = isBattle
			break
		end
	end
end

function DungeonManager:getNearlyBattleIndex()
	if self._battlePoints then
		for i,v in ipairs(self._battlePoints) do
			if not v.finished then
				return v.index
			end
		end
	end
	return nil
end

function DungeonManager:enterDungeon()
	if self:getDungeonMapId() ~= MapManager:getMapId() then
		return
	end

	if self:isRace() then
		-- UIHandler:getSystemUi():addTouchMask() -- 竞速模式添加遮罩，防止在Cosplay UI弹出前，点击传送石退出
		UIHandler:addPrepareBattleTouchMask()
		self:noMove()
		self:enterDungeonFinishRequest()
	-- elseif self:isSecret() then
	-- 	self:enterDungeonFinishRequest()
	end
	self._levelDungeon = false
	self._countDownStart = false
	self._timeOut = false
	self:setBattleStart(false)
--	self:createQuitNpc()
	self:updateFinishNpc()
	self:addPreNpcsToMap()
	EM:notify("onDungeonUi",{status = "open", type = self._dungeonInfo.type})
	app:sendMsg("NewTeamReadyAndSettingController", "outDungeons")
	if self:isRace() then
		EM:notify("onBottomNodeChanged",{status = "hide"})
		EM:notify("onSkillChangeNodeChanged", {status = "show"}) --显示技能切换按钮
	end
	-- 检查是否正在播放剧情，然后隐藏bnpc
	if StoryManager:isEnterStoryMode() then
		self:hideAllBNpcs()
	end

	UIHandler:setDesktopTipVisible(false)
	UIHandler:setDesktopAdvertVisible(false)

	EM:notify("onEnterDungeon")
end

function DungeonManager:goOutDungeon()
	if self:getDungeonMapId() == MapManager:getMapId() then
		return
	end

	self:closeDungeonUi()
	self:clearBNpcs()
	-- self._dungeonTotalConfig = nil
	self._subConfig = nil
	self._battlePoints = nil
	self._dungeonInfo.type = nil
end

-- function DungeonManager:resetToAlivePoint()
-- 	if self._battleIndex and self._battlePoints then
-- 		local destX
-- 		local lIndex = self._battleIndex - 1
-- 		local lPoint = self._battlePoints[lIndex]
-- 		if lIndex >= 1 and lPoint then
-- 			destX = lPoint.posx
-- 		elseif lIndex == 0 then
-- 			local qNpcId = tonumber(self._subConfig.quitNPCID)
-- 			local npc = NpcManager:getNpcById(qNpcId)
-- 			if npc then
-- 				destX = npc:getPositionX()
-- 			end
-- 		else
-- 			local point = self._battlePoints[self._battleIndex]
-- 			if point then
-- 				destX = point.posx - point.radius - 10
-- 			end
-- 		end

-- 		if destX then
-- 			self:teleportCharacter(destX)
-- 		end
-- 	end
-- end

function DungeonManager:teleportCharacter(destX)
	local TeamModel = app:getInst("TeamModel")
	if TeamModel:hasTeam() then
	   	TeamManager:resetTeamPosition(destX)
	    if TeamModel:isMyTeam() then
	       	FieldManager:refreshMyCharacterPositionToServer(true)
		end
	else
		local myCharacter = FieldManager:getMyCharacter()
		myCharacter:showLocationX(destX)
		myCharacter:setTargetX(destX)
		FieldManager:refreshMyCharacterPositionToServer(true)
	end
end

function DungeonManager:failedBattle()
	self:resetBattleStatus()
	self:setAlreadyBattle(self._battleIndex,false)
end

function DungeonManager:createSingleNpc(npcId,x)
	if not npcId then return end
    local npcConfig = NpcManager:getNpcConfigById(npcId)
	local npcUid = NpcManager:generateNpcUid()
    local npc = NpcFactory:createNpc(npcConfig,npcUid,false,nil,true)
    if npc then
    	npc:allNameNodeVisibility(true)
        npc:currentMarkVisibility(true)
        npc:stopShowUpHead(false)
    end
    app:dispatchCustomEvent("EVENT_REFRESH_DUNGEON_SCRIPT",{npc = npc})
    if not npc or not x then return end
    npc:showLocationX(x)
end

function DungeonManager:createSingleBNpc(npcId,x)
	if not npcId then return end
	local npcC = NpcManager:getBNpcConfigById(npcId)
	local npc = NpcFactory:createBNpc(npcC,false)
    if npc and x then
    	--让Npc和战斗高度一致
    	npc:setOffsetY(Constant.BattleLinesSpaceY[#Constant.BattleLinesSpaceY])
    	npc:showLocationX(x)
    	npc:setOriginalScale(0.98)
    end
    return npc
end

--function DungeonManager:createQuitNpc()
--	if not self._subConfig then return end
--	self:createSingleNpc(self._subConfig.quitNPCID)
--end

function DungeonManager:createFinishNpc()
	if not self._subConfig then return end
	local npcId = self._subConfig.finishNPCID
	if not NpcManager:getNpcById(npcId) then
		self:createSingleNpc(npcId)
	end
end

function DungeonManager:createBattlePointNpcs()
	if not self._battlePoints then
		return
	end
	NpcManager:loadBNpcConfigs()
	for i, battlePoint in ipairs(self._battlePoints) do
		if not battlePoint.finished and battlePoint.formationInfo then
			for j,formation in ipairs(battlePoint.formationInfo) do
				local npcId = tonumber(formation.BNPCID)
				local posx
				local st = battlePoint.info[tonumber(formation.PosID)]
				posx = st and st.pos or 0
				-- print("createBattlePoints >>>>>>>>>> npcId = ",npcId,"  posx = ",posx)
				local npc = self:createSingleBNpc(npcId,posx)
				self:addPreBNpc({npc = npc,index = battlePoint.index,z = st and st.z or 0})
			end
		end
	end
end

function DungeonManager:clearPreBNpcs()
	self._preBNpcs = {}
end

function DungeonManager:addPreBNpc(npcS)
	if not npcS.npc then return end
	npcS.npc:retain()
	table.insert(self._preBNpcs,npcS)
end

function DungeonManager:addPreNpcsToMap()
	if not self._preBNpcs then return end
	local map = MapManager:getMap()
	-- if not map then return end
	if cc.isDead(map) then return end
	for i,npcS in ipairs(self._preBNpcs) do
		map:addNpcToLine(2,npcS.npc,npcS.z)
		npcS.npc:setLocalZOrder(npcS.z)
		npcS.npc:release()
		npcS.npc:rayCastFoothold(npcS.npc:getPositionX())
		self:addBNpcByIndex(npcS.index,npcS.npc)
	end

	self:clearPreBNpcs()
end

function DungeonManager:getBattlePointsByIndex(index)
	if not self._battlePoints then return end
	for i,v in ipairs(self._battlePoints) do
		if v.index == index then
			return v
		end
	end
	return nil
end

function DungeonManager:updateBattlePointStatus()
	if not self._battlePoints or not self._dungeonInfo then return end
	for k,v in pairs(self._dungeonInfo.battleStatusInfos) do
		local battlePoint = self:getBattlePointsByIndex(v.index)
		if battlePoint then
			battlePoint.id = v.id
			battlePoint.finished = v.finished
			if v.finished then
				self:deleteBNpcByIndex(v.index)
			end
		end
	end

	if self:isDungeonInBattle()  then
		local TeamModel = app:getInst("TeamModel")
		if not self._battleIndex or not TeamModel:isLeader() then
			self._battleIndex = self:getNearlyBattleIndex()
		end
	end
end

function DungeonManager:updateDungeonInfo()
	self:updateBattlePointStatus()
	self:updateFinishNpc()
end

function DungeonManager:updateFinishNpc()
	if not self._countDownStart and self:isDungeonFinished() then
		self:createFinishNpc()
		self:dungeonFinished()
		self:dungeonCountDownStart()
	end
	if self:isDungeonTimeOut() and not self._timeOut then
		self._timeOut = true
		self:dungeonAway()
	end
end

function DungeonManager:isDungeonFinished()
	if self._dungeonInfo and self._dungeonInfo.status == "finished" then
		return true
	end
	return false
end

function DungeonManager:isDungeonTimeOut()
	if self._dungeonInfo and self._dungeonInfo.status == "timeout" then
		return true
	end
	return false
end

function DungeonManager:isDungeonInBattle()
	if self._dungeonInfo and self._dungeonInfo.status == "inBattle" then
		return true
	end
	return false
end

function DungeonManager:isInDungeon()
	return self:getDungeonMapId() == MapManager:getMapId()
end

-- 是跨服副本（需要屏蔽一些队伍操作）
function DungeonManager:isCrossDungeon()
	if self:isInDungeon() then
		return self._dungeonInfo.isCrossDungeon
	end
	return false
end

-- 是否为剧情副本（假副本）
function DungeonManager:isTaskDungeon()
	if self._dungeonType and self._dungeonType == 1 then return true end
	return false 
end

function DungeonManager:isDungeonArea(cx)
	local isArea = false
	if self:getDungeonMapId() == MapManager:getMapId() and self._battlePoints then
		for _,v in ipairs(self._battlePoints) do
			if cx >= (v.posx - v.radius) and cx <= (v.posx + v.radius) and not v.finished then
				isArea = true
				break
			end
		end
	end
	return isArea
end

function DungeonManager:updateFrame(dt)
	if StoryManager:isEnterStoryMode() then return end
	if self:isBattleStart() then return end
	if self:getDungeonMapId() ~= MapManager:getMapId() then return end
	if not self._battlePoints then return end
	if self:isDungeonInBattle() then return end
	local TeamModel = app:getInst("TeamModel")
	local character = FieldManager:getMyCharacter()
	local cx = character:getPositionX()
	if TeamModel:hasTeam() and not TeamModel:isLeader() then return end
	local flagBattleRadiusChanged = false
	if self._initMapScale ~= MapManager:getMapScale() then
		flagBattleRadiusChanged = true
		self._initMapScale = MapManager:getMapScale()
	end
	local realRadius = 0
	for _,v in ipairs(self._battlePoints) do
		if flagBattleRadiusChanged then
			v.radius = self:updateBattleRadius(v.battleId)
		end
		realRadius = v.radius
		if cx >= (v.posx - realRadius) and cx <= (v.posx + realRadius) and not v.finished then
			if not v.already then
				self:teleportCharacter(v.posx - realRadius - 15)
				self:dungeonBattleStart(self._dungeonInfo.dungeonUUID,v.index, v.battleId)
				break
			end
		end
	end
end

function DungeonManager:getAwayNpcC()
	local rx = 0
	local npcId = 0
	if self:getDungeonMapId() == MapManager:getMapId() then
		if self._subConfig then
			local npcC
			if self:isDungeonFinished() or self:isDungeonTimeOut() then
				npcId = tonumber(self._subConfig.finishNPCID)
				npcC = NpcManager:getNpcConfigById(npcId)
			else
				npcId = tonumber(self._subConfig.quitNPCID)
				npcC = NpcManager:getNpcConfigById(npcId)
			end
			if npcC and npcC.coordinate then
				rx = tonumber(npcC.coordinate)
			end
		end
	end
	return rx,npcId
end

function DungeonManager:dungeonCountDownStart()
	if self._dungeonType == 1 then return end
	if self._countDownStart then return end
	self._countDownStart = true

	local iCountDown = 10
	if self._subConfig and self._subConfig.dungeonExtraSeconds then
		iCountDown = tonumber(self._subConfig.dungeonExtraSeconds)
	end
	EM:notify("onDungeonCountDown",{second = iCountDown})
	-- EM:notify("onDungeonCountDown",{second = tonumber(S("dungeonExtraSeconds")) or 10})

	-- 设置通关奖励数据
	self._dungeonSubId = self:getDungeonSubId()
	self._hasShowPassAward = false
end

function DungeonManager:dungeonFinished()
	EM:notify("onDungeonFinished")
end

function DungeonManager:dungeonAway()
	local function away()
		if self:isCrossDungeon() then
			-- 跨服副本，必须要调用C2S_LeaveDungeon退出副本
			self:leaveDungeonRequest()
		else
			local TeamModel = app:getInst("TeamModel")
			if (TeamModel:hasTeam() and TeamModel:isLeader()) or (not TeamModel:hasTeam()) then
				self:leaveDungeonRequest()
			end
		end
	end

	if self._countDownStart then
		self._countDownStart = false
		-- 完成的倒计时退出服务器做
		-- away()
		self:clearDungeon()
	elseif self._timeOut then
		away()
	end
end

function DungeonManager:getDungeonName()
	local dungeonSubId = self:getDungeonSubId()
	if not dungeonSubId then return "" end

	local dungeonSubInfo = GD:queryDungeonSubById(dungeonSubId)
	if dungeonSubInfo then
		return L(dungeonSubInfo.name)
	end

	return ""
end

function DungeonManager:getDungeonRaceTime()
	if not self._subConfig then return end
	local time1 = 0
	local time2 = 0
	local time3 = 0
	local rmc = GD:queryDungeonRaceModeById(self._subConfig.ID)
	if rmc then
		local r1 = rmc.timeline3
		local r2 = rmc.timeline2
		local r3 = rmc.timeline1
		time1 = TimeUtil.secondsToTime(tonumber(r1))
		time2 = TimeUtil.secondsToTime(tonumber(r2))
		time3 = TimeUtil.secondsToTime(tonumber(r3))
	end

	return time1,time2,time3,self:isRace()
end

function DungeonManager:getDungeonResidueTime()
	if not self._dungeonInfo then return end
	local residueTime = self._dungeonInfo.finishClock - (app.session:getServerTime() or app:getTime())
 	return TimeUtil.secondsToTime(math.floor(residueTime))
end

function DungeonManager:getTotalTime()
	if not self._dungeonInfo then return "00:00:00" end

	local t = math.floor(app:getServerTime()) - self._dungeonInfo.createClock
	return TimeUtil.secondsToTime(t)
end

function DungeonManager:getDungeonTime()
	if not self._dungeonInfo then return end

	local residueTime = self._dungeonInfo.finishClock - math.floor(app:getServerTime())
	local totalTime = tonumber(self._subConfig.deadline)
	local moveTime = totalTime - residueTime
	local percent = moveTime / totalTime * 100

	local _,time = TimeUtil.secondsToStr(math.floor(moveTime),1)
	local isStop = self:isDungeonFinished()
	return self:isRace(),time,percent,isStop
end

function DungeonManager:getDungeonLeaderProgress()
	if not self._battlePoints then return end

	local totalNum = 0
	local idsArray = {}
	if self._subConfig and self._subConfig.bossPosIDs then
		idsArray = string.split(self._subConfig.bossPosIDs,";")
		totalNum = #idsArray
	end

	local function isLeader(index)
		for _,idx in ipairs(idsArray) do
			if tonumber(idx) == tonumber(index) then
				return true
			end
		end
		return false
	end

	local count = 0
	for _,v in ipairs(self._battlePoints) do
		if v.finished then
			if isLeader(v.index) then
				count = count + 1
			end
		end
	end

	return count .. "/" .. totalNum
end

function DungeonManager:getDungeonMonsterProgress()
	if not self._battlePoints then return end

	local totalNum = 0
	local idsArray = {}
	if self._subConfig and self._subConfig.bossPosIDs then
		idsArray = string.split(self._subConfig.bossPosIDs,";")
		totalNum = #idsArray
	end

	-- local function isLeader(index)
	-- 	for _,idx in ipairs(idsArray) do
	-- 		if tonumber(idx) == tonumber(index) then
	-- 			return true
	-- 		end
	-- 	end
	-- 	return false
	-- end

	local count = 0
	for _,v in ipairs(self._battlePoints) do
		if v.finished then
			-- if isLeader(v.index) then
			count = count + 1
			-- end
		end
	end

	return "" .. count
end

function DungeonManager:closeDungeonUi()
	EM:notify("onDungeonUi",{status = "close", type = self._dungeonInfo.type})
	EM:notify("onBottomNodeChanged",{status = "show"})
	EM:notify("onSkillChangeNodeChanged", {status = "hide"})
	UIHandler:setDesktopTipVisible(true)
	UIHandler:setDesktopAdvertVisible(true)
	if self:isDungeonFinished() then
		app:sendMsg("RewardModel", "checkShowAdvert", Enums.ActivitySubType.FirstRecharge)
	end
end


function DungeonManager:addBNpcByIndex(index,npc)
	self._bnpcs[index] = (self._bnpcs[index] == nil) and {} or self._bnpcs[index]
	table.insert(self._bnpcs[index],npc)
end

function DungeonManager:deleteBNpcByIndex(index)
	local npcs = self._bnpcs[index]
	if not npcs then return end
	for i,npc in ipairs(npcs) do
		local line = npc:getLine()
		self:dispatchEvent({name = "map_DeleteNpc",npc = npc,line = line})
	end
	self._bnpcs[index] = {}
end

function DungeonManager:clearBNpcs()
	self._bnpcs = {}
end

function DungeonManager:deleteAllBNpcs()
	if not self._bnpcs then return end
	for index, npcs in pairs(self._bnpcs) do
		for _, npc in pairs(npcs) do
			local line = npc:getLine()
			self:dispatchEvent({name = "map_DeleteNpc",npc = npc,line = line})
		end
	end
	self:clearBNpcs()
end

function DungeonManager:hideAllBNpcs()
	if not self._bnpcs then return end
	for _,npcs in pairs(self._bnpcs) do
		for _,npc in pairs(npcs) do
			npc:allVisibility(false)
		end
	end
end

function DungeonManager:showAllBNpcs()
	if not self._bnpcs then return end
	for _,npcs in pairs(self._bnpcs) do
		for _,npc in pairs(npcs) do
			if not cc.isDead(npc) then
				npc:allVisibility(true)
			end
		end
	end
end

-- 显示通关奖励
function DungeonManager:showPassDungeonAward()
	if not self._dungeonSubId or self._hasShowPassAward then
		return 
	end

	local dungeonSubInfo = GD:queryDungeonSubById(self._dungeonSubId)
	if dungeonSubInfo and tonumber(dungeonSubInfo.dungeonPoint) > 0 then
		-- 显示界面
		local view = DungeonPassAwardView.new()
		view:onCloseView(function()
			view:removeFromParent()
		end)
		UIHandler:addPopupUi(view)
		view:updateView(dungeonSubInfo.dungeonPoint, L(dungeonSubInfo.name), dungeonSubInfo.dungeonBossIcon)
		view:show()
	end

	self._dungeonSubId = nil
	self._hasShowPassAward = true
end

return DungeonManager
